<template>
  <div class="overview-view">
    <!-- 顶部统计卡片 -->
    <div class="stats-grid">
      <StatCard
        title="总人口"
        :value="formatNumber(totalPopulation)"
        icon="👥"
        trend="+2.3%"
        color="blue"
      />
      <StatCard
        title="总资源"
        :value="formatNumber(totalResourceValue)"
        icon="💎"
        trend="+5.7%"
        color="green"
      />
      <StatCard
        title="舰队数量"
        :value="shipsStore.fleets.length"
        icon="🚀"
        trend="+1"
        color="purple"
      />
      <StatCard
        title="外交关系"
        :value="`${diplomacyStore.alliedFactions.length}/${diplomacyStore.neutralFactions.length}/${diplomacyStore.hostileFactions.length}`"
        icon="🤝"
        trend="稳定"
        color="orange"
      />
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- 帝国概况 -->
        <div class="panel-section">
          <h3 class="section-title">
            <span class="title-icon">🏛️</span>
            帝国概况
          </h3>
          <div class="empire-info">
            <div class="info-item">
              <span class="label">帝国名称:</span>
              <span class="value">人类联邦</span>
            </div>
            <div class="info-item">
              <span class="label">成立时间:</span>
              <span class="value">{{ formatGameTime(gameStore.gameTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">控制星系:</span>
              <span class="value">{{ controlledSystems }}</span>
            </div>
            <div class="info-item">
              <span class="label">殖民星球:</span>
              <span class="value">{{ colonizedPlanets }}</span>
            </div>
          </div>
        </div>

        <!-- 最近事件 -->
        <div class="panel-section">
          <h3 class="section-title">
            <span class="title-icon">📰</span>
            最近事件
          </h3>
          <div class="recent-events">
            <div 
              v-for="event in recentEvents" 
              :key="event.id"
              class="event-item"
              :class="`event-${event.type}`"
            >
              <div class="event-icon">{{ getEventIcon(event.type) }}</div>
              <div class="event-content">
                <div class="event-title">{{ event.title }}</div>
                <div class="event-time">{{ formatRelativeTime(event.createdAt) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 成就进度 -->
        <div class="panel-section">
          <h3 class="section-title">
            <span class="title-icon">🏆</span>
            成就进度
          </h3>
          <div class="achievements">
            <div 
              v-for="achievement in recentAchievements" 
              :key="achievement.id"
              class="achievement-item"
              :class="{ unlocked: achievement.unlocked }"
            >
              <div class="achievement-icon">{{ achievement.icon }}</div>
              <div class="achievement-info">
                <div class="achievement-name">{{ achievement.name }}</div>
                <div class="achievement-progress">
                  <div class="progress-bar">
                    <div 
                      class="progress-fill" 
                      :style="{ width: `${achievement.progress}%` }"
                    ></div>
                  </div>
                  <span class="progress-text">{{ achievement.progress }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 资源生产图表 -->
        <div class="panel-section">
          <h3 class="section-title">
            <span class="title-icon">📊</span>
            资源生产趋势
          </h3>
          <div class="chart-container">
            <ResourceChart :data="resourceChartData" />
          </div>
        </div>

        <!-- 建筑状态 -->
        <div class="panel-section">
          <h3 class="section-title">
            <span class="title-icon">🏭</span>
            建筑状态
          </h3>
          <div class="building-status">
            <div 
              v-for="category in buildingCategories" 
              :key="category.id"
              class="building-category"
            >
              <div class="category-header">
                <span class="category-icon">{{ category.icon }}</span>
                <span class="category-name">{{ category.name }}</span>
                <span class="category-count">{{ category.count }}</span>
              </div>
              <div class="category-progress">
                <div class="progress-bar">
                  <div 
                    class="progress-fill" 
                    :style="{ width: `${category.efficiency}%` }"
                  ></div>
                </div>
                <span class="efficiency-text">{{ category.efficiency }}% 效率</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 科技进度 -->
        <div class="panel-section">
          <h3 class="section-title">
            <span class="title-icon">🔬</span>
            科技研究
          </h3>
          <div class="research-status">
            <div v-if="currentResearch" class="current-research">
              <div class="research-info">
                <div class="research-name">{{ currentResearch.name }}</div>
                <div class="research-progress">
                  <div class="progress-bar">
                    <div 
                      class="progress-fill" 
                      :style="{ width: `${currentResearch.progress}%` }"
                    ></div>
                  </div>
                  <span class="progress-text">{{ currentResearch.progress }}%</span>
                </div>
                <div class="research-eta">预计完成: {{ currentResearch.eta }}</div>
              </div>
            </div>
            <div v-else class="no-research">
              <p>当前没有进行中的研究项目</p>
              <button class="start-research-btn" @click="goToTechnology">
                开始研究
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useGameStore, useResourcesStore, useBuildingsStore, useTechnologyStore, useShipsStore, useDiplomacyStore } from '@/stores'
import StatCard from '@/components/ui/StatCard.vue'
import ResourceChart from '@/components/ui/ResourceChart.vue'

const gameStore = useGameStore()
const resourcesStore = useResourcesStore()
const buildingsStore = useBuildingsStore()
const technologyStore = useTechnologyStore()
const shipsStore = useShipsStore()
const diplomacyStore = useDiplomacyStore()

// 计算属性
const totalPopulation = computed(() => {
  try {
    // 检查资源存储是否已初始化
    if (!resourcesStore?.isInitialized) {
      return 0
    }
    
    // 检查方法是否存在
    if (typeof resourcesStore.getResourceAmount !== 'function') {
      console.warn('getResourceAmount method not available in OverviewView')
      return 0
    }
    
    return resourcesStore.getResourceAmount('population') || 0
  } catch (error) {
    console.warn('Error accessing totalPopulation in OverviewView:', error)
    return 0
  }
})

const totalResourceValue = computed(() => {
  return Object.values(resourcesStore.resources).reduce((sum, amount) => sum + amount, 0)
})

const controlledSystems = computed(() => {
  // 这里应该从游戏状态中获取控制的星系数量
  return 3
})

const colonizedPlanets = computed(() => {
  // 这里应该从游戏状态中获取殖民星球数量
  return 5
})

const recentEvents = computed(() => {
  return gameStore.currentEvents?.slice(0, 5) || []
})

const recentAchievements = computed(() => {
  return gameStore.achievements?.slice(0, 4).map(achievement => ({
    ...achievement,
    progress: achievement.unlocked ? 100 : Math.floor(Math.random() * 80) // 模拟进度
  })) || []
})

const resourceChartData = computed(() => {
  // 模拟资源生产数据
  return {
    labels: ['能量', '金属', '水晶', '稀有金属'],
    datasets: [{
      label: '生产量',
      data: [
        resourcesStore.getResourceProduction('energy'),
        resourcesStore.getResourceProduction('metals'),
        resourcesStore.getResourceProduction('crystals'),
        resourcesStore.getResourceProduction('rare_metals')
      ],
      backgroundColor: ['#00d4ff', '#ff6b6b', '#4ecdc4', '#ffe66d']
    }]
  }
})

const buildingCategories = computed(() => {
  const categories = [
    { id: 'infrastructure', name: '基础设施', icon: '🏗️' },
    { id: 'industrial', name: '工业建筑', icon: '🏭' },
    { id: 'research', name: '研究设施', icon: '🔬' },
    { id: 'military', name: '军事建筑', icon: '⚔️' }
  ]

  return categories.map(category => ({
    ...category,
    count: buildingsStore.getBuildingsByCategory(category.id).length,
    efficiency: Math.floor(Math.random() * 20) + 80 // 模拟效率
  }))
})

const currentResearch = computed(() => {
  const activeProjects = technologyStore.activeResearchProjects
  if (activeProjects.length === 0) return null

  const project = activeProjects[0]
  return {
    name: project.name || '未知研究',
    progress: Math.floor(project.progress * 100),
    eta: formatTime(project.estimatedTime || 0)
  }
})

// 方法
function formatNumber(num: number): string {
  if (num >= 1000000000) {
    return (num / 1000000000).toFixed(1) + 'B'
  } else if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  } else {
    return Math.floor(num).toString()
  }
}

function formatGameTime(time: number): string {
  const totalMinutes = Math.floor(time / 60000)
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60
  return `${hours}小时${minutes}分钟`
}

function formatRelativeTime(timestamp: number): string {
  const now = Date.now()
  const diff = now - timestamp
  const minutes = Math.floor(diff / 60000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小时前`
  
  const days = Math.floor(hours / 24)
  return `${days}天前`
}

function formatTime(seconds: number): string {
  if (seconds < 60) return `${Math.floor(seconds)}秒`
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`
  return `${Math.floor(seconds / 86400)}天`
}

function getEventIcon(type: string): string {
  const icons: Record<string, string> = {
    opportunity: '✨',
    crisis: '⚠️',
    discovery: '🔍',
    diplomatic: '🤝',
    military: '⚔️',
    economic: '💰',
    random: '🎲'
  }
  return icons[type] || '📰'
}

function goToTechnology() {
  gameStore.setCurrentView('technology')
}
</script>

<style scoped>
.overview-view {
  padding: 1rem;
  height: 100%;
  overflow-y: auto;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  height: calc(100% - 200px);
}

.left-panel,
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.panel-section {
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 1rem;
  backdrop-filter: blur(5px);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0 0 1rem 0;
  font-size: 1.1rem;
  font-weight: bold;
  color: #00d4ff;
}

.title-icon {
  font-size: 1.2rem;
}

.empire-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.25rem 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #cccccc;
  font-size: 0.9rem;
}

.value {
  color: #ffffff;
  font-weight: 500;
}

.recent-events {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  max-height: 200px;
  overflow-y: auto;
}

.event-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.5rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border-left: 3px solid #00d4ff;
}

.event-item.event-crisis {
  border-left-color: #ff4444;
}

.event-item.event-opportunity {
  border-left-color: #44ff44;
}

.event-icon {
  font-size: 1.2rem;
  min-width: 20px;
}

.event-content {
  flex: 1;
}

.event-title {
  font-size: 0.9rem;
  font-weight: 500;
  color: #ffffff;
}

.event-time {
  font-size: 0.8rem;
  color: #888888;
}

.achievements {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.achievement-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.5rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  opacity: 0.6;
}

.achievement-item.unlocked {
  opacity: 1;
  background: rgba(0, 212, 255, 0.1);
}

.achievement-icon {
  font-size: 1.5rem;
  min-width: 24px;
}

.achievement-info {
  flex: 1;
}

.achievement-name {
  font-size: 0.9rem;
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 0.25rem;
}

.achievement-progress {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00d4ff, #0099cc);
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 0.8rem;
  color: #cccccc;
  min-width: 35px;
}

.chart-container {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.building-status {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.building-category {
  padding: 0.5rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.category-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.category-icon {
  font-size: 1.2rem;
}

.category-name {
  flex: 1;
  font-weight: 500;
}

.category-count {
  color: #00d4ff;
  font-weight: bold;
}

.category-progress {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.efficiency-text {
  font-size: 0.8rem;
  color: #cccccc;
  min-width: 60px;
}

.research-status {
  min-height: 100px;
}

.current-research {
  padding: 0.75rem;
  background: rgba(0, 212, 255, 0.1);
  border-radius: 6px;
  border: 1px solid rgba(0, 212, 255, 0.3);
}

.research-name {
  font-weight: 500;
  color: #00d4ff;
  margin-bottom: 0.5rem;
}

.research-progress {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.research-eta {
  font-size: 0.8rem;
  color: #cccccc;
}

.no-research {
  text-align: center;
  padding: 1rem;
  color: #888888;
}

.start-research-btn {
  margin-top: 0.5rem;
  padding: 0.5rem 1rem;
  background: #00d4ff;
  color: #000000;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.start-research-btn:hover {
  background: #0099cc;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .overview-view {
    padding: 0.5rem;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 0.5rem;
  }
  
  .main-content {
    gap: 1rem;
  }
  
  .panel-section {
    padding: 0.75rem;
  }
}
</style>